<template>
  <el-table 
    height="calc(100% - 30px)"
    :data="tableList"
    ref="table" 
  >
    <el-table-column type="index" label="序号" width="50" />
    <el-table-column label="商品名称" prop="drugName" width="200">
      <template v-slot="slot">
        <template v-if="slot.row.search">
          <deliverySerach
            @selectDrug="onSelectDrug"
            :drugType="drugType"
            ref="searchDrug"
          />
        </template>
        <template v-else>{{slot.row.drugName}}</template>
      </template>
    </el-table-column>
    <el-table-column label="供应商" prop="supplyName" />
    <el-table-column :label="costPriceLabel" prop="costPrice" width="120">
      <template slot-scope="scope">
        <template v-if="!scope.row.search">
          {{ formatMoney(scope.row.costPrice) }}
        </template>
      </template>
    </el-table-column>
    <el-table-column v-if="drugType === 2" label="红冲" prop="redPun">
      <template slot-scope="scope">
        <template v-if="!scope.row.search">
          {{ scope.row.redPun }}%
        </template>
      </template>
    </el-table-column>
    <el-table-column v-if="drugType === 2" label="成本价" prop="selfPrice">
      <template slot-scope="scope">
        <template v-if="!scope.row.search">
          {{ formatMoney(scope.row.selfPrice) }}
        </template>
      </template>
    </el-table-column>
    <el-table-column label="批次号" prop="batchNo" />
    <template v-if="drugType != 2 && drugType != 1">
      <el-table-column label="有效期" prop="termOfValidity" width="145" />
    </template>
    <el-table-column label="库存数量" prop="stock">
      <template v-slot="slot">
        <template v-if="!slot.row.search">
          <template v-if="slot.row.minLeftCount > 0">{{slot.row.stock + slot.row.packageUnit + slot.row.minLeftCount  + slot.row.doseUnit}}</template>
          <template v-else>{{slot.row.stock + slot.row.packageUnit }}</template>
        </template>
      </template>
    </el-table-column>
    <el-table-column label="包装规格" prop="coefficientName" />
    <el-table-column label="换算系数" prop="coefficient" />
    <el-table-column label="出库数量" prop="quantity" width="140">
      <template v-slot="slot">
        <template v-if="!slot.row.search">
          <template v-if="!readOnly">
            <el-input-number
              :class="{error: slot.row.errorConfig && slot.row.errorConfig.quantity}"
              v-model="slot.row.quantity"
              @change="onChangeNum(slot.row)"
              style="width: 120px"
              :controls="false"
              :min="0"
            />
          </template>
          <template v-else>{{slot.row.quantity }}</template>
        </template>
      </template>
    </el-table-column>
    <el-table-column label="出库总数量" prop="deliveryNum" width="120">
      <template v-slot="slot">
        <template v-if="!slot.row.search">
          <template v-if="!readOnly">
            <el-input-number
              :class="{error: slot.row.errorConfig && slot.row.errorConfig.deliveryNum}"
              v-model="slot.row.deliveryNum"
              @blur="validatorField(slot.row, slot.column.property)"
              style="width: 100px"
              :controls="false"
              :min="0"
            />
          </template>
          <template v-else>{{slot.row.deliveryNum + slot.row.packageUnit }}</template>
        </template>
      </template>
    </el-table-column>
    <template v-if="!readOnly">
      <el-table-column label="操作">
        <template v-slot="slot">
          <template v-if="!slot.row.search">
            <el-button type="text" @click="onDel(slot.$index)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </template>
    <!-- <template v-if="operation != 2">
      <el-table-column label="数量单位" prop="packageUnit" width="100" >
        <template v-slot="slot">
          <template v-if="!slot.row.search">
            <template v-if="slot.row.minLeftCount > 0">
              <el-select v-model="slot.row.useUnit" placeholder="请选择" @change="onChangeUnit(slot.row)">
                <el-option
                  v-for="item in slot.row.unitOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
            <template v-else>{{slot.row.packageUnit}}</template>
          </template>
        </template>
      </el-table-column>
    </template> -->
  </el-table>
</template>

<script>
import { formatMoney } from "@/utils/index";
import Validator from "async-validator";
import deliverySerach from "./search";

export default {
  name: "deliveryTable",
  props: {
    // 0-新增,1-编辑,2-查看,3-即将过期药品出库
    operation: {
      type: Number,
      default: 0
    },
    // 只读
    readOnly: {
      type: Boolean,
      default: false // 默认可编辑
    },
    // 药品类型:1-饮片,2-颗粒剂,7-西药及中成药
    drugType: {
      type: Number,
      default: 0
    }
  },
  components: { deliverySerach },
  data() {
    return {
      rules: {
        quantity: {
          type: 'number',
          required: true,
          validator(rule, value, callback) {
            if(!value) {
              callback(new Error("请填写出库数量"));
            }
            if(value <= 0) {
              callback(new Error("出库数量必须大于0"));
            }
            callback();
          },
        },
        deliveryNum: {
          type: 'number',
          required: true,
          validator(rule, value, callback) {
            if(!value) {
              callback(new Error("请填写出库总数量"));
            }
            callback();
          },
        },
      },
      validObj: {},
      tableList: [],
    };
  },
  computed: {
    costPriceLabel() {
      if(this.drugType === 1 || this.drugType === 2) {
        return "克进货价";
      }
      return "进货价";
    }
  },
  methods: {
    formatMoney,
    onSelectDrug(row) {
      let list = this.tableList.filter(item => {
        return row.id == item.warehousingDetailId;
      });
      if(list.length > 0) {
        this.$message.error('所选药品已添加!');
        return;
      }
      let data = {
        batchNo: row.batchNo,
        costPrice: row.costPrice,
        createTime: "",
        deliveryNo: "",
        quantity: 0,
        deliveryNum: 0,
        minDeliveryNum:0,
        drugId: row.drugId,
        drugManufactor: row.drugManufactor,
        drugName: row.drugName,
        drugSpec: row.drugSpec,
        packageUnit: row.packageUnit,
        doseUnit:row.doseUnit,
        useUnit:row.packageUnit,
        pharmacyId: this.pharmacyId,
        salePrice: row.salePrice,
        stock: row.leftCount,
        minLeftCount: row.minLeftCount,
        termOfValidity: row.termOfValidity,
        warehousingDetailId: row.id,
        drugType: row.drugType,
        redPun: row.redPun,
        selfPrice: row.selfPrice,
        totalDose: row.totalDose,
        coefficient: row.coefficient,
        coefficientName: row.coefficientName,
        supplyName: row.drugManufactor,
        unitOptionFlage: 0,
        unitOption:[
          {
            value:'0',
            label:row.packageUnit,
          },
          {
            value:'1',
            label:row.doseUnit,
          },
        ],
      }; 
      this.tableList.splice(this.tableList.length - 1, 0, data);
      // 禁止切换药品类型
      this.$emit("disabled", true);
    },
    onDel(index) {
      if(this.$refs.table) {
        this.$refs.table.toggleRowSelection(index, false);
      } else {
        this.tableList.splice(index, 1);
      }
      this.tableList.splice(index, 1);
      if(this.tableList.length === 1) {
        // 药品被清空？允许切换药品类型
        this.$emit("disabled", false);
      }
    },
    // 更改出库数量，自动计算实际出库数量
    onChangeNum(e) {
      // 实际出库数量 = 出库数量 * 换算系数
      e.deliveryNum = e.quantity * e.coefficient;
      e.minDeliveryNum = 0;
      if(e.deliveryNum > e.stock) {
        // e.quantity = e.leftCount;
        this.$message.error('出货量大于现有库存');
      }
      this.validatorField(e, "quantity");
      this.validatorField(e, "deliveryNum");
      // if(e.unitOptionFlage == 0){
      //   e.deliveryNum = e.quantity;
      //   e.minDeliveryNum = 0;

      //   if(e.quantity > e.leftCount) {
      //     // e.quantity = e.leftCount;
      //      this.$message.error('出货量大于现有库存');
      //   }
      // } else {
      //   e.minDeliveryNum = e.quantity;
      //   e.deliveryNum = 0;

      //   let maxC =  e.leftCount*e.totalDose + e.minLeftCount
      //   if(e.minDeliveryNum > maxC) {
      //     // e.quantity =maxC;
      //      this.$message.error('出货量大于现有库存');
      //   }
      // }
    },
    // onChangeUnit(e) {
    //   e.quantity = 0;
    //   if(e.useUnit == e.packageUnit){
    //     var obj = e.unitOption[0];
    //     e.unitOptionFlage = 0;
    //     e.useUnit = obj.label;
    //     e.deliveryNum = e.quantity;
    //     e.minDeliveryNum = 0;
    //     e.stock = e.leftCount;
    //   } else {
    //     var obj = e.unitOption[1];
    //     e.unitOptionFlage = 1;
    //     e.useUnit = obj.label;
        
    //     e.minDeliveryNum =  e.quantity;
    //     e.deliveryNum = 0;
    //     e.stock = e.leftCount*e.totalDose + e.minLeftCount;
    //   }
    // },
    setTableList(list) {
      this.$set(this, "tableList", list);
      this.$nextTick(() => {
        this.tableList.forEach(item => {
          if(!item.search) {
            this.$refs.table.toggleRowSelection(item, true);
          }
        });
      });
    },
    // 清空已选列表
    clearSelection() {
      if(this.$refs.table) {
        this.$refs.table.clearSelection();
      }
    },
    // 返回待提交的选择列表
    getSelectList() {
      let res = [];
      this.tableList.forEach(item => {
        if(!item.search) {
          let detail = {
            ...item
          };
          // 删除无关的属性
          delete detail.unitOption;
          delete detail.unitOptionFlage;
          delete detail.errorConfig;
          res.push(detail);
        }
      });
      return res;
    },
    // 表格输入验证
    validator(call) {
      let selectList = this._selectList();
      let rules = this.rules;
      let v = new Validator(rules);
      this.validObj.count = 0;
      this.validObj.backCall = call;
      this.validObj.errors = [];
      selectList.forEach((item, index) => {
        this._validatorItem(item, index, v);
      });
      if(selectList.length == 0) {
        this.validObj.backCall(false, this.validObj.errors);
      }
    },
    // 属性输入验证
    validatorField(row, fileid) {
      if(!this.rules[fileid] || !this.rules[fileid].required) return;
      let rules = {
        [fileid]: this.rules[fileid]
      };
      let v = new Validator(rules);
      let obj = {
        [fileid]: row[fileid]
      }
      v.validate(obj, (errors, fileds) => {
        if(errors) {
          this._setErrorStyle(row, fileid, true);
        } else {
          this._setErrorStyle(row, fileid, false);
        }
      });
    },
    _validatorItem(item, index, v) {
      let selectList = this._selectList();
      v.validate(item, (errors, fileds) => {
        this.validObj.count ++;
        if(errors) {
          this.validObj.errors.push({ index, fileds });
        }
        for(let filed in item) {
          if(fileds && fileds[filed]) {
            this._setErrorStyle(item, filed, true);
          } else {
            this._setErrorStyle(item, filed, false);
          }
        }
        if(selectList.length === this.validObj.count) {
          this.validObj.backCall(this.validObj.errors.length > 0 ,this.validObj.errors);
        }
      });
    },
    // 列表单设置error样式
    _setErrorStyle(row, fileid, error) {
      let errorConfig = row.errorConfig;
      if(!errorConfig) {
        errorConfig = {};
        this.$set(row, "errorConfig", errorConfig);
      }
      this.$set(errorConfig, fileid, error);
    },
    // 选中的列表
    _selectList() {
      return this.tableList.filter(item => {
        return !item.search;
      });
    }
  }
}
</script>